//
//  AddressSelectController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/6/9.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class AddressSelectController: CBBaseViewController {
    
    var tbSelect: UITableView!
    //选择的区域
    weak var selectArea:Variable<(title:String, value:String)>?
    
    var arrAreaModels:[[AreaModel]] = [[AreaModel]]()
    var arrTitle:[String] = [String]()
    var arrIds:Variable<[String]> = Variable([String]())
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "选择省份"
        
        tbSelect = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(tbSelect)
        tbSelect.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        tbSelect.dataSource = self
        tbSelect.delegate = self
        tbSelect.tableFooterView = UIView()
        
        arrIds.asObservable()
            .subscribe(onNext:{ [unowned self] tpArrIds in
                if tpArrIds.count == 0 {
                    self.title = "选择省份"
                } else if tpArrIds.count == 1 {
                    self.title = "选择城市"
                } else if tpArrIds.count == 2 {
                    self.title = "选择区域"
                }
                //选择了之后
                if tpArrIds.count == self.arrAreaModels.count && tpArrIds.count != 3 {
                    SVProgressHUD.show()
                    NetworkTool.requestData(url: ActionURL.GET_AREA, param: ["pid":tpArrIds.last ?? "0"])
                        .map({ (json) -> [AreaModel]? in
                            return AreaModel.mj_objectArray(withKeyValuesArray: json["rows"].arrayObject) as? [AreaModel]
                        }).catchErrorJustReturn(nil)
                        .observeOn(MainScheduler.instance)
                        .subscribe(onNext: { [unowned self] tpArr in
                            self.push(stack: &self.arrAreaModels, element: tpArr)
                            self.tbSelect.reloadData()
                            self.tbSelect.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
                            SVProgressHUD.dismiss()
                        }).disposed(by: self.disposeBag)
                } else if tpArrIds.count == self.arrAreaModels.count - 2 { //返回的操作
                    self.pop(stack: &self.arrAreaModels)
                    self.tbSelect.reloadData()
                    self.tbSelect.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
                } else if tpArrIds.count == 3 { //选择完毕退出
                    self.selectArea?.value = (title:self.arrTitle.joined(separator: ""),value:tpArrIds.joined(separator: "|"))
                    self.navigationController?.popViewController(animated: true)
                }
            }).disposed(by: disposeBag)
        
    }
    
    override func backAction() {
        if arrIds.value.count == 0 {
            self.navigationController?.popViewController(animated: true)
        } else {
            self.pop(stack: &arrIds.value)
            self.pop(stack: &arrTitle)
        }
    }
    
}

extension AddressSelectController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrAreaModels.last?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "AddressSelectCell")
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "AddressSelectCell")
            cell?.accessoryType = .disclosureIndicator
        }
        cell?.textLabel?.text = arrAreaModels.last?[indexPath.row].name
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = arrAreaModels.last?[indexPath.row]
        push(stack: &arrTitle, element: model?.name)
        push(stack: &arrIds.value, element: model?.id)
    }
    
}

extension AddressSelectController {
    
    //入栈
    func push<T>(stack: inout [T], element:T?) {
        if let relElement = element {
            stack.append(relElement)
        }
    }
    //出栈
    func pop<T>(stack: inout [T]) {
        if stack.count > 0 {
            stack.remove(at: stack.count - 1)
        }
    }
    
}



